<!-- 二级菜单动态面包屑 -->
<template>
  <Bread>
    <BreadItem to="/">首页</BreadItem>
    <XtxBreadItem v-if="category.top" :to="`/category/${category.top.id}`">{{ category.top.name }}</XtxBreadItem>
    <Transition name="fade-right" mode="out-in">
      <XtxBreadItem v-if="category.sub" :key="category.sub.id">{{ category.sub.name }}</XtxBreadItem>
    </Transition>
  </Bread>
</template>
<script>
import { computed } from "vue"
import { useRoute } from "vue-router"
import { useStore } from "vuex"

export default {
  name: 'SubBread',
  setup(props) {
    const route = useRoute()
    const store = useStore()
    // 通过计算属性得到，二级类目的名称和ID，一级类目的名称和ID
    const category = computed(() => {
      const obj = {}
      store.state.category.list.forEach(top => {
        top.children && top.children.forEach(sub => {
          // 确认路径是否一致, 同时监听了url的变化
          if (sub.id == route.params.id) {
            obj.top = { id: top.id, name: top.name }
            obj.sub = { id: sub.id, name: sub.name }
          }
        })
      })
      return obj
    })

    return {
      category
    }
  }
}
</script>